package com.izkml.mlyun.hotreload.websocket.handler;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.izkml.mlyun.hotreload.enums.ErrorEnums;
import com.izkml.mlyun.hotreload.websocket.WebSocketUtil;
import com.izkml.mlyun.hotreload.websocket.message.ReceiveMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.RandomAccessFile;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
public class LogWebSocketHandler extends TextWebSocketHandler {

    private static final Map<String, RandomAccessFile> fileReaders = new ConcurrentHashMap<>();
    private static final Map<String, ScheduledExecutorService> executors = new ConcurrentHashMap<>();
    private static final Map<String, Boolean> acceptLog = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("Connection established. WebSocketSession: {}", session.getRemoteAddress());

//        if (!FileUtil.exist(Const.APP.LOG_FILE)) {
//            String errMsg = StrUtil.format("Error find log file: {}", Const.APP.LOG_FILE);
//            log.warn(errMsg);
//            WebSocketUtil.sendError(session, ErrorEnums.SERVER_ERROR, errMsg);
////            session.close(new CloseStatus(1011, errMsg));
//            return;
//        }
//        acceptLog.put(session.getId(), Boolean.FALSE);
//
//        RandomAccessFile reader = new RandomAccessFile(Const.APP.LOG_FILE, "r");
//        WebSocketUtil.follow(session, reader, fileReaders, executors, acceptLog);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
    }

    public void handleReceiveMessage(WebSocketSession session, ReceiveMessage receiveMessage){
//        try {
//            String method = receiveMessage.getMethod();
//            if ("logSwitch".equals(method)) {
//                acceptLog.put(session.getId(), "ON".equals(String.valueOf(receiveMessage.getParams())));
//            }
//        } catch (Exception e){
//            log.error("WebSocket异常",e);
//            WebSocketUtil.sendError(session, ErrorEnums.SERVER_ERROR, e.getMessage());
//        }
    }

}
